package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //用户登录
        if (StringUtils.isNotBlank(loginDto.getPhone()) && StringUtils.isNotBlank(loginDto.getPassword())) {
            ApUser dbUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
            //用户不存在
            if (dbUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "该用户不存在");
            }

            //判断密码
            String password = loginDto.getPassword();
            String salt = dbUser.getSalt();
            String realPassword = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            //密码错误
            if (!dbUser.getPassword().equals(realPassword)){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "密码错误");
            }

            //构造返回的对象
            String token = AppJwtUtil.getToken(dbUser.getId().longValue());
            dbUser.setSalt("");
            dbUser.setPassword("");
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            map.put("user",dbUser);
            return ResponseResult.okResult(map);

        //游客登录
        }else {
            String token = AppJwtUtil.getToken(0L);
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
